//
//  PeripheralOptionsView.swift
//  WCHBLEApp
//
//  Created by 娟华 胡 on 2021/3/22.
//

import UIKit

class PeripheralOptionsView: UIView {

    @IBOutlet weak var advertiseDataLabel: UILabel!
    @IBOutlet weak var maunuIDLabel: UILabel!
    @IBOutlet weak var nodeIDLabel: UILabel!
    @IBOutlet weak var stateNodeLabel: UILabel!
    @IBOutlet weak var tagLabel: UILabel!
    @IBOutlet weak var packetCountLabel: UILabel!
    
    @IBAction func okAction(_ sender: Any) {
        
        UIView.animate(withDuration: 0.7) {
            self.alpha = 0
        } completion: {[weak self] (finish) in
            self?.removeFromSuperview()
        }
    }
    
    public func setAdvertisementData(advertisementData: [String : Any]?) {
        
        if let manufacturerData = advertisementData?["kCBAdvDataManufacturerData"] as? Data {
            assert(manufacturerData.count >= 7)
            
            var dataStr = "0x"
            for i in 0 ..< manufacturerData.count {
                dataStr += String.init(format: "%02x", manufacturerData[i])
            }
            self.advertiseDataLabel.text = dataStr
            //0d00 - TI manufacturer ID
            //Constructing 2-byte data as little endian (as TI's manufacturer ID is 000D)
            let manufactureID = UInt16(manufacturerData[0]) + UInt16(manufacturerData[1]) << 8
            self.maunuIDLabel.text = String(format: "0x%04X", manufactureID)
            
            //fe - the node ID that I have given
            let nodeID = manufacturerData[2]
            self.nodeIDLabel.text = String(format: "0x%02X", nodeID)

            //05 - state of the node (something that remains constant
            let state = manufacturerData[3]
            self.stateNodeLabel.text = String(format: "0x%02X", state)

            //c6f - is the sensor tag battery voltage
            //Constructing 2-byte data as big endian (as shown in the Java code)
            let batteryVoltage = UInt16(manufacturerData[4]) << 8 + UInt16(manufacturerData[5])
            self.tagLabel.text = String(format: "0x%04X", batteryVoltage)

            //32- is the BLE packet counter.
            let packetCounter = manufacturerData[6]
            self.packetCountLabel.text = String(format: "0x%02X", packetCounter)
        }
    }
}
